﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Jayrock.Json.Conversion;
using System.Text.RegularExpressions;


namespace NJL.Web
{
    public partial class SinaCallBack : BasePageVisitor
    {
        protected string AUTH_GUID;

        protected void Page_Load(object sender, EventArgs e)
        {
            string strFromWebSiteCode = Session["FromWebSiteCode"].ToString();
            string strFromDomain = Session["FromDomain"].ToString();
            string strFromUrl = Session["FromUrl"].ToString();
            string strFromLoginType = Session["FromLoginType"].ToString();

            try
            {
                oAuthSina oauth = new oAuthSina();
                if (Request["oauth_verifier"] != null)
                {
                    oauth.token = Session["oauth_token"].ToString();
                    oauth.tokenSecret = Session["oauth_token_secret"].ToString();
                    oauth.Verifier = Request["oauth_verifier"].ToString();
                    oauth.AccessTokenGet();
                    Session["oauth_token"] = oauth.token; ;
                    Session["oauth_token_secret"] = oauth.tokenSecret;
                    Session["oauth_user_id"] = oauth.tokenUserId;

                    oauth.token = Session["oauth_token"].ToString();
                    oauth.tokenSecret = Session["oauth_token_secret"].ToString();
                    string basic = "http://api.t.sina.com.cn/";
                    string url = basic + "users/show/" + Session["oauth_user_id"].ToString() + ".json";
                    string strUserInfo = oauth.oAuthWebRequest(oAuthSina.Method.GET, url, String.Empty);

                    //string strID = Regex.Match(strUserInfo, "\"id\":([\\d]*),").Groups[1].Value;
                    //string strScreenName = Regex.Match(strUserInfo, "\"screen_name\":\"(([\\u4e00-\\u9fa5]|[a-zA-Z0-9])*)\",").Groups[1].Value;
                    //string strName = Regex.Match(strUserInfo, "\"name\":\"(([\\u4e00-\\u9fa5]|[a-zA-Z0-9])*)\",").Groups[1].Value;

                    //SinaUserInfo sinaUserInfo = new SinaUserInfo();
                    //sinaUserInfo.ID = strID;
                    //sinaUserInfo.SCREEN_NAME = strScreenName;
                    //sinaUserInfo.NAME = strName;
                    SinaUserInfo sinaUserInfo = Royalsoft.Common.JsonHelper.JsonDeserialize<SinaUserInfo>(strUserInfo);
                    if (null != sinaUserInfo)
                    {
                        Model.NJL_USER model = new BLL.NJL_USER().GetModelBySinaOpenID(sinaUserInfo.id);

                        if (null == model)
                        {
                            model = new Model.NJL_USER();
                            model.ID = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(100, 999).ToString();
                            model.NJL_SYS_BASE_ID = strFromWebSiteCode;
                            model.USER_NAME = sinaUserInfo.screen_name;
                            model.WEIBO_OPENID = sinaUserInfo.id;
                            model.TYPE_CODE = "2";//直接激活
                            model.INTEGRAL = 0;
                            model.CREATE_DATE_TIME = System.DateTime.Now;

                            new BLL.NJL_USER().Add(model);

                            //添加个人信息
                            Model.NJL_PERSON modelPerson = new Model.NJL_PERSON();
                            modelPerson.ID = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(100, 999).ToString();
                            modelPerson.NJL_SYS_BASE_ID = strFromWebSiteCode;
                            modelPerson.CREATE_DATE_TIME = DateTime.Now;
                            modelPerson.NJL_USER_ID = model.ID;
                            new BLL.NJL_PERSON().Add(modelPerson);

                            Session.Clear();
                            Session.Abandon();
                            Session.Add("userid", model.ID);
                            Session.Add("username", model.USER_NAME);
                            Session.Add("usertype", model.TYPE_CODE);

                            string userType = model.TYPE_CODE;
                            if (model.TYPE_CODE == "0")
                            {
                                model.TYPE_CODE = "2";
                                new BLL.NJL_USER().Update(model);
                            }
                            string strToURL = "";
                            //如果未激活先到激活页面
                            if (userType == "0")
                            {
                                strToURL = "/RegisterTow.aspx";
                            }
                            else if (strFromUrl == "")
                            {
                                strToURL = "/";
                            }
                            else if (strFromUrl != "")
                            {
                                strToURL = strFromUrl;
                            }
                            else
                            {
                                strToURL = "/";
                            }

                            ShareSession.ShareSessionFormatter.Serialize(ShareSession.ShareSessionFormatter.FormatterType.Soap);
                            AUTH_GUID = Session["AUTH_GUID"].ToString();

                            string strURL = "http://" + strFromDomain + "/GetUserSessions.aspx?AUTH_GUID=" + AUTH_GUID + "&tourl=" + strToURL + "&logintype=" + strFromLoginType + "";
                            Response.Redirect(strURL, false);
                        }
                        else
                        {
                            Session.Clear();
                            Session.Abandon();
                            Session.Add("userid", model.ID);
                            Session.Add("username", model.USER_NAME);
                            Session.Add("usertype", model.TYPE_CODE);

                            string userType = model.TYPE_CODE;
                            string strToURL = "";
                            //如果未激活先到激活页面
                            if (userType == "0")
                            {
                                strToURL = "/RegisterTow.aspx";
                            }
                            else if (strFromUrl == "")
                            {
                                strToURL = "/";
                            }
                            else if (strFromUrl != "")
                            {
                                strToURL = strFromUrl;
                            }
                            else
                            {
                                strToURL = "/";
                            }

                            ShareSession.ShareSessionFormatter.Serialize(ShareSession.ShareSessionFormatter.FormatterType.Soap);
                            AUTH_GUID = Session["AUTH_GUID"].ToString();

                            string strURL = "http://" + strFromDomain + "/GetUserSessions.aspx?AUTH_GUID=" + AUTH_GUID + "&tourl=" + strToURL + "&logintype=" + strFromLoginType + "";
                            Response.Redirect(strURL, false);
                        }
                    }
                    else
                    {
                        //Response.Redirect("/",true);
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "<script language='javascript' defer>window.opener.location.href = '/';window.close();</script>");
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/LoginToSina.aspx?websitecode=" + strFromWebSiteCode + "&domain=" + strFromDomain + "&url=" + strFromUrl);
                //Response.Write(ex.Message.ToString());
            }

        }
    }

    public class SinaUserInfo
    {
        public string id { get; set; }
        public string screen_name { get; set; }
        public string name { get; set; }
    }
}